package test;

public class Sort {

    private static void swap(int[] arr,int x,int y){
        int temp=arr[x];
        arr[x]=arr[y];
        arr[y]=temp;
    }


    public static void bubbleSort(int[] arr){
        for (int i=0;i<arr.length;i++){
            for (int j=i+1;j<arr.length;j++){
                if(arr[i]>arr[j]) swap(arr,i,j);
            }
        }
    }

    public static void selectSort(int[] arr){
        int minIndex;
        for (int i = 0; i < arr.length; i++) {
            minIndex=i;
            for (int j = i; j < arr.length; j++) {
                if(arr[j]<arr[minIndex]) minIndex=j;
            }
            swap(arr,minIndex,i);
        }
    }

    public static void insertSort(int[] arr){
        int pre,current;
        for (int i = 1; i < arr.length; i++) {
            pre=i-1;
            current=arr[i];
            while (pre>=0 && arr[pre]>current){
                arr[pre+1]=arr[pre];
                pre--;
            }
            arr[pre+1]=current;
        }
    }

    public static void mergeSort(int[] arr,int low,int high){
        int mid=(low+high)/2;
        if(low<high){
            mergeSort(arr,low,mid);
            mergeSort(arr,mid+1,high);
            merge(arr,low,mid,high);
        }
    }
    private static void merge(int[] arr,int low,int mid,int high){
        int[] temp=new int[high-low+1];
        int i=low;
        int j=mid+1;
        int k=0;

        while (i<=mid && j<=high){
            if(arr[i]<arr[j]) temp[k++]=arr[i++];
            else temp[k++]=arr[j++];
        }

        while (i<=mid) temp[k++]=arr[i++];

        while (j<=high) temp[k++]=arr[j++];

        for (i = 0; i < temp.length; i++) {
            arr[i+low]=temp[i];
        }
    }

    public static void quickSort(int[] arr,int left,int right){
        if(left<right){
            int index=getIndex(arr,left,right);
            quickSort(arr,left,index-1);
            quickSort(arr,index+1,right);
        }


    }

    private static int getIndex(int[] arr,int left,int right){
        int pivot=arr[left];
        while (left<right){
            while (left<right && arr[right]>=pivot) right--;
            arr[left]=arr[right];
            while (left<right && arr[left]<=pivot) left++;
            arr[right]=arr[left];
        }
        arr[left]=pivot;
        return left;
    }

    public static void heapSort(int[] arr){
        for(int i=arr.length/2;i>=0;i--) buildMaxHeap(arr,i,arr.length);

        for (int i=arr.length-1;i>=0;i--){
            swap(arr,0,i);
            buildMaxHeap(arr,0,i);
        }
    }

    private static void buildMaxHeap(int[] arr,int start,int length){
        int temp=arr[start];
        for (int i=2*start+1;i<length;i=2*i+1){
            if(i+1<length && arr[i]<arr[i+1]) i++;
            if (temp>=arr[i]) break;
            swap(arr,start,i);
            start=i;
        }
    }



}
